from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.contrib import admin
from . import service
import json
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response


def start_service(request):
    return service.start_service()


def calculate(request):
    if 'Port' in request.POST and request.POST['Port'] != '':
        port_name = request.POST['Port']

    if 'Data' in request.POST and request.POST['Data'] != '':
        data = json.loads(request.POST['Data'])

    return service.predict(port_name=port_name, data=data)


def custom_admin_view(request):
    context = admin.site.each_context(request)
    context.update({
        'title': '其他说明'
    })

    template = 'admin/custom_view.html'
    return render(request, template, context)


@api_view(['POST'])
def new_service(request):
    try:
        service.start_service()
        data = {'status': 'Finished'}
        return Response(data, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({'error': e.args[0]}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
def new_calculate(request):
    # try:
    result = service.new_predict(request.data)
    return Response(result, status=status.HTTP_200_OK)
    # except Exception as e:
    #     return Response({'error': e.args[0]}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def test1(request):
    try:
        print('test running')
        result = service.test()
        return Response(result, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({'error': e.args[0]}, status=status.HTTP_400_BAD_REQUEST)
